<!--
 * @Author: lmh
 * @Date: 2021-07-27 17:34:49
 * @LastEditTime: 2021-08-11 14:36:43
 * @LastEditors: lmh
 * @Description: 
-->
<template>
  <h1>{{ msg }}</h1>
  <p>{{ count }}</p>
  <p>{{ doubleCount }}</p>
  <p ref="refTest"></p>

  <!-- teleport -->
  <ModuleButton></ModuleButton>

  <!-- Emits选项 -->
  <Emits @my-click="onClick"></Emits>
</template>

<script>
import {
  reactive,
  computed,
  onMounted,
  onUnmounted,
  toRefs,
  ref,
  watch,
} from "vue";
import ModuleButton from "./ModelButton.vue";
import Emits from "./Emits.vue";
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  components: {
    ModuleButton,
    Emits,
  },
  methods: {
    onClick() {
      console.log("click me!");
    },
  },
  setup() {
    const { count, doubleCount } = initCount();

    // 使用元素的引用
    const refTest = ref(null);

    // 侦听器
    watch(count, (val, oldVal) => {
      const p = refTest.value;
      p.textContent = `counter change from ${oldVal} to ${val}`;
    });

    return { count, doubleCount, refTest };
  },
};
function initCount() {
  const data = reactive({
    count: 1,
    doubleCount: computed(() => data.count * 2),
  });

  let timer;

  onMounted(() => {
    console.log("onMounted");
    timer = setInterval(() => {
      data.count++;
    }, 1000);
  });

  onUnmounted(() => {
    console.log("onUnmounted");
    clearInterval(timer);
  });

  return toRefs(data);
}
</script>
